//app.js
import fly from './lib/js/apiConfig'
// let livePlayer = requirePlugin('live-player-plugin')
App({
  fly: fly,
  onLaunch: function (options) {
    if (options.scene) {
      this.globalData.scene = options.scene
    }
    var that = this
    //强制更新
    const updateManager = wx.getUpdateManager()
    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      
    })
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success: function (res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }else{
            updateManager.applyUpdate()
          }
        }
      })
    })
    updateManager.onUpdateFailed(function () {
      // 新的版本下载失败
      wx.showModal({
        title: '更新提示',
        content: '新版本下载失败',
        showCancel: false
      })
    })
    wx.getSystemInfo({
      success: function (res) {
        console.log(res)
        if (res.platform == "ios") {
          wx.setStorageSync("deviceType", 'IOS')
        } else if (res.platform == "android") {
          wx.setStorageSync("deviceType", 'Android')
        }
        if(res.SDKVersion){
          wx.setStorageSync("sdkversion", res.SDKVersion)
        }
        let modelmes = res.model;
        if (modelmes.search('iPhone X') != -1 || modelmes.search('unknow') != -1 || modelmes.search('iPhone 11') != -1 || modelmes.search('iPhone 12') != -1) {
          that.globalData.isIphoneX = true
        } else {
          that.globalData.isIphoneX = false
        }
        wx.setStorageSync('modelmes', modelmes)
        that.globalData.navHeight = Math.abs(res.statusBarHeight) + 46;
        that.globalData.windowHeight = res.windowHeight
        that.globalData.windowWidth = res.windowWidth
        that.globalData.height = Math.abs(res.statusBarHeight)
        console.log(that.globalData.windowWidth,that.globalData.windowHeight)
        // that.globalData.titleBarHeight = (wx.getMenuButtonBoundingClientRect().bottom - that.globalData.height - wx.getMenuButtonBoundingClientRect().height) * 2 + wx.getMenuButtonBoundingClientRect().height

      },
      failure() {
        that.globalData.statusBarHeight = 0
        that.globalData.titleBarHeight = 0
      }
    })

    if (options.query.page) {
      let parms = {
        page: options.query.page,
        spread_code: options.query.spread_code
      }
      fly.post('/mall/v1/common/pageCount/index', parms).then(function (res) {

      })
    }
    // 登录
    wx.login({
      success: res => {
        console.log(res)
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        this.globalData.code = res.code
      }
    })
  },
  onShow(options) {
    //从推荐官跳转过来的店铺id
    // if(options.referrerInfo.extraData){
    //   if(options.referrerInfo.extraData.store_id){
    //     this.globalData.store_id=options.referrerInfo.extraData.store_id
    //   }
      
    // }
    
    //bdp数据统计
    if (options.query.sign) {
      var sign=options.query.sign
      fly.post('/mall/v1/common/message/point',{sign:sign}).then(function (res) {
        
       
      })
    }
    //分享店铺过来的店铺id
    if (options.query.store_id) {
      this.globalData.store_id= options.query.store_id
    }
    //直播需要线上实测
    if (options.query.custom_params) {
      wx.setStorageSync("spread_code", options.query.custom_params)
    }
     
    if (options.query.spread_code) {
      var timestamp = Date.parse(new Date());
      timestamp = timestamp / 1000;
      wx.setStorageSync("time", timestamp)
      wx.setStorageSync("spread_code", options.query.spread_code)
      this.bindSpread(options.query.spread_code,timestamp);
    }
    if (options.query.scene){
      const scene = decodeURIComponent(options.query.scene)
      let arr = scene.split(',')
      var timestamp = Date.parse(new Date());
      timestamp = timestamp / 1000;
      if (arr.length >= 2) {
        wx.setStorageSync("time", timestamp)
        wx.setStorageSync("spread_code", arr[1])
        this.bindSpread(arr[1], timestamp);
      }
    }

    let that = this;
    // 分享卡片入口场景才调用getShareParams接口获取以下参数
    if (options.scene == 1007 || options.scene == 1008 || options.scene == 1044) {
      livePlayer.getShareParams()
        .then(res => {
          // console.log('get room id', res.room_id) // 房间号
          // console.log('get openid', res.openid) // 用户openid
          // console.log('get share openid', res.share_openid) // 分享者openid，分享卡片进入场景才有
          // console.log('get custom params', res.custom_params) // 开发者在跳转进入直播间页面时，页面路径上携带的自定义参数，这里传回给开发者
          if (res.share_openid) {
            that.getSpreadCode(res.share_openid)
          } else if (res.custom_params) {
            wx.setStorageSync("spread_code", res.custom_params)
            var timestamp = Date.parse(new Date());
            timestamp = timestamp / 1000;
            wx.setStorageSync("time", timestamp)
          }
        }).catch(err => {
          console.log('get share params', err)
        })
    }
  },
  //实时获取最新的wx.login下的code
  getLoginCode(e){
    var that=this
    wx.login({
      success: res => {
        console.log(res)
        that.globalData.code = res.code
      }
    })

  },
  //计算有多少个字节
  numLength(str){
    if (typeof str != "string"){  
      str += "";  
  }  
  return str.replace(/[^\x00-\xff]/g,"01").length;  
  },
  //消息跳转对应二级页
  goMess(id,page_id,params){
    console.log(page_id,params)
    // return
    switch (page_id) {
      case 1:
        this.hideMess(id)
        break;
        case 3:
        this.hideMess(id)
        break;
        case 7:
        wx.navigateTo({
          url: '/shop/pages/refundDetail/refundDetail?redid='+id+'&id='+params.id
        })
        break;
        case 5:
        this.hideMess(id)
        wx.navigateTo({
          url: '/packageB/pages/redPacket/redPacket?redid='+id
        })
        break;
        case 8:
        wx.navigateTo({
          url: '/packageA/pages/detail/detail?redid='+id+'&id='+params.id+'&activity_type='+2
        })
        break;
        case 15:
          wx.navigateTo({
            url: '/packageD/pages/accountDetail/accountDetail?redid='+id
          })
          break;
          case 10:
            wx.navigateTo({
              url: '/packageA/pages/detailCut/detailCut?redid='+id+'&id='+params.id+'&from_type=' + 0
            })
            break;
            case 20:
              wx.navigateTo({
                url: '/packageA/pages/detail/detail?redid='+id+'&id='+params.id
              })
              break;
              case 2:
                wx.navigateTo({
                  url: '/packageA/pages/news/news?id='+params.id
                })
                this.hideMess(id)
              break;
              case 18:
                this.hideMess(id)
               this.getUserInfo()
               break;
               case 6:
                this.hideMess(id)
                wx.navigateTo({
                  url: '/packageB/pages/useCoupon/useCoupon'
                })
               break;
               case 9:
                this.hideMess(id)
        wx.navigateTo({
          url: '/packageD/pages/getPacket/getPacket'
        })
               break;
              case 23:
        this.hideMess(id)
              wx.navigateTo({
                url: '/packageB/pages/myDiscuss/myDiscuss?reply_id=' + params.id 
              })
              break;
      default:
        // this.hideMess(id)
        // wx.navigateTo({
        //   url: '/packageD/pages/getPacket/getPacket'
        // })
       
        
    }

  },
   //判断各种类型跳转
   goWay(e, f, g,img) {
     console.log(e)
     var that=this
    if (e == 1) {
      wx.navigateTo({
        url: '/packageA/pages/detail/detail?id=' + f,
      })
    } else if (e == 2) {
      wx.navigateTo({
        url: '/packageA/pages/list/list?id=' + f + "&title=" + g,
      })
    }else if (e == 3) {
      wx.navigateTo({
        url: '/packageB/pages/live/live',
      })
    } else if (e == 4) {
      wx.navigateTo({
        url: '/packageA/pages/news/news?id=' + f + "&title=" + g,
      })
    } else if (e == 10) {
      wx.navigateTo({
        url: '/packageA/pages/detail/detail?id=' + f,
      })
    } else if (e == 11) {
      wx.navigateTo({
        url: '/packageA/pages/list/list?id=' + f + "&title=" + g,
      })
    } else if (e == 12) {
      wx.navigateTo({
        url: '/packageA/pages/seckill/seckill',
      })
    } else if (e == 13) {
      wx.navigateTo({
        url: '/packageA/pages/newBody/newBody?id=' + f + "&title=" + g,
      })
    } else if (e == 14) {
      wx.switchTab({
        url: '/pages/member/member',
      })
    } else if (e == 15) {
      wx.navigateTo({
        url: '/packageA/pages/listing/listing?type=' + 1 + "&title=" + g
      })
    } else if (e == 16) {
      wx.navigateTo({
        url: '/packageA/pages/detail/detail?id=1&activity_type=1',
      })
    } else if (e == 17) {
      wx.navigateTo({
        url: '/packageB/pages/redPacket/redPacket',
      })
    } else if (e == 18) {
      wx.navigateTo({
        url: '/packageA/pages/detail/detail?id=' + f + '&activity_type=2',
      })
    } else if (e == 19) {
      wx.navigateToMiniProgram({
        appId: 'wx3572af653727c2cf',
        path: 'pages/index/index',
        extraData: {
          foo: 'bar'
        },
        envVersion: 'release',
        success(res) {
          // 打开成功
        },
        fail(res) {
        }

      })
    } else if (e == 20) {
      wx.navigateTo({
        url: '/packageC/pages/newWelfare/newWelfare',
      })
    } else if (e == 21) {
      wx.navigateTo({
        url: '/packageA/pages/detailCut/detailCut?id=' + f,
      })
    } else if (e == 22) {
      wx.navigateTo({
        url: '/packageC/pages/newProduct/newProduct',
      })
    } else if (e == 23) {
      wx.navigateTo({
        url: '/packageB/pages/live/live',
      })
    } else if (e == 24) {
      wx.navigateTo({
        url: '/packageC/pages/bargainArea/bargainArea',
      })
    } else if (e == 26) {
      wx.navigateTo({
        url: '/packageA/pages/subject/subject?id=' + f + "&title=" + g,
      })
    } else if (e == 27) {
      if (wx.getStorageSync('token')) {
        if (that.data.store_id) {
          wx.navigateTo({
            url: '/shop/pages/detail/detail?id=' + f + '&store_id=' + that.data.store_id,
          })
        } else {
          wx.showModal({
            title: '提示',
            content: '您无店主权益！您要立即开店吗',
            success(res) {
              if (res.confirm) {
                // if (!wx.getStorageSync('token')) {
                //   wx.navigateTo({
                //     url: '/packageD/pages/authorize/authorize',
                //   });
                //   return
                // } 
                // that.getUserInfo()
                wx.navigateTo({
                  url: '/shop/pages/shopGift/shopGift',
                })
              }
            }
          })
        }
      } else {
        wx.navigateTo({
          url: '/packageD/pages/authorize/authorize'
        })
      }

    } else if (e == 28) {
      wx.navigateTo({
        url: '/shop/pages/detail/detail?id=' + f + '&activity_type=4',
      })
    } else if (e == 29) {
      // if (!wx.getStorageSync('token')) {
      //   wx.navigateTo({
      //     url: '/packageD/pages/authorize/authorize',
      //   });
      //   return
      // } 
      // this.getUserInfo()
      wx.navigateTo({
        url: '/shop/pages/shopGift/shopGift',
      })
    } else if (e == 30) {
      // if (!wx.getStorageSync('token')) {
      //   wx.navigateTo({
      //     url: '/packageD/pages/authorize/authorize',
      //   });
      //   return
      // } 
      // this.getUserInfo()
      wx.navigateTo({
        url: '/shop/pages/inviteStore/inviteStore',
      })
    }else if (e == 31) {
      wx.navigateTo({
        url: '/packageA/pages/hotSell/hotSell?id=' + f + "&title=" + g,
      })
    } else if (e == 32) {
      wx.navigateTo({
        url: '/packageA/pages/hotMoney/hotMoney',
      })
    } else if (e == 33) {
      wx.navigateTo({
        url: '/packageA/pages/discount/discount',
      })
    } else if (e == 35) {
      wx.navigateTo({
        url: '/packageA/pages/topic/topic?id=' + f + "&title=" + g,
      })
    }else if(e == 36){
      wx.navigateTo({
        url: '/packageA/pages/distin/distin',
      })
    } else if (e == 37) {
      wx.navigateTo({
        url: '/packageA/pages/rush/rush',
      })
    } else if (e == 38) {
      wx.navigateTo({
        url: '/packageB/pages/useCoupon/useCoupon',
      })
    }else if(e == 39){
      wx.navigateTo({
        url: '/packageD/pages/integralCenter/integralCenter',
      })
    }else if(e == 40){
      var urls = [];
      var src = img;//获取data-src
      urls.push(src);
      wx.previewImage({
        current: src, // 当前显示图片的http链接
        urls: urls
      })
    }else if(e == 41){
      wx.navigateTo({
        url: '/packageD/pages/luckDraw/luckDraw',
      })
    } else if (e == 42) {
      wx.navigateTo({
        url: 'plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id=' + f 
      })
    } else if (e == 43) {
      wx.navigateTo({
        url: '/packageB/pages/original/original?id=' + f + "&title=" + g,
      })
    } else if (e == 44) {
      wx.navigateTo({
        url: '/packageB/pages/artList/artList',
      })
    }else if (e == 45) {
      wx.navigateTo({
        url: '/packageB/pages/crafList/crafList',
      })
    }
  },
  //获取用户地理位置权限
  getPermission:function(obj){
    wx.chooseLocation({
      success: function (res) {    
          obj.setData({
              addr: res.address      //调用成功直接设置地址
          })                
      },
      fail:function(){
          wx.getSetting({
              success: function (res) {
                console.log(res)
                  var statu = res.authSetting;
                  if (!statu['scope.userLocation']) {
                      wx.showModal({
                          title: '是否授权当前位置',
                          content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
                          success: function (tip) {
                              if (tip.confirm) {
                                  wx.openSetting({
                                      success: function (data) {
                                          if (data.authSetting["scope.userLocation"] === true) {
                                              wx.showToast({
                                                  title: '授权成功',
                                                  icon: 'success',
                                                  duration: 1000
                                              })
                                              //授权成功之后，再调用chooseLocation选择地方
                                              wx.chooseLocation({
                                                  success: function(res) {
                                                      obj.setData({
                                                          addr: res.address
                                                      })
                                                  },
                                              })
                                          } else {
                                              wx.showToast({
                                                  title: '授权失败',
                                                  icon: 'success',
                                                  duration: 1000
                                              })
                                          }
                                      }
                                  })
                              }
                          }
                      })
                  }
              },
              fail: function (res) {
                  wx.showToast({
                      title: '调用授权窗口失败',
                      icon: 'success',
                      duration: 1000
                  })
              }
          })
      }
  })        
 },
      //获取个人信息判断跳转逻辑
   getUserInfo(type) {
    var that = this
    fly.post('/v1/user/getUserInfo').then(function (res) {
      // if(res.data.is_alert_new_go_packet==1){
      //   wx.navigateTo({
      //     url: '/packageD/pages/animation/animation',
      //   })
      // }else{
      //   wx.navigateTo({
      //     url: '/shop/pages/shopGift/shopGift',
      //   })
      // }
      wx.navigateTo({
        url: '/shop/pages/shopGift/shopGift',
      })
     
     
    })
  },
   //消除消息红点
  hideMess(id) {
    var that=this
    fly.get('/v1/msg/read',{id:id}).then(function (res) {
      

    })
  },
  //获取我的系统消息红点数字
  getRedNum() {
    var that=this
    fly.get('/v1/user/getUserInfo').then(function (res) {
      if (res.data.read_count>0) {
        wx.setTabBarBadge({
          index: 3,//下标
          text: res.data.read_count>99?'99+':res.data.read_count+''
  })
        that.globalData.redShow=true
        that.globalData.myRedNum=res.data.read_count>99?'99+':res.data.read_count
      }
      else {
        wx.removeTabBarBadge({ //移除taBar右上角的文本
          index: 3,//tabBar下标
       })
        that.globalData.redShow=false
        that.globalData.myRedNum=0
      }

    })
  },
  //无系统tab页获取我的系统消息红点数字
  getRedNum2() {
    var that=this
    fly.get('/v1/user/getUserInfo').then(function (res) {
      if (res.data.read_count>0) {
        that.globalData.redShow=true
        that.globalData.myRedNum=res.data.read_count>99?'99+':res.data.read_count
      }
      else {
        that.globalData.redShow=false
        that.globalData.myRedNum=0
      }
    })
  },
  //后台获取用户oppenid
  sendCode: function (e) {
    var that = this
    if (wx.getStorageSync('token')) {
      setTimeout(() => {
        // fly.post('/v1/user/getUserInfo').then(function (res) {
          // if (res.data.bind_mini_openid == 0) {
            wx.login({
              success: res_one => {
                fly.post('/v1/addMiniOpenid', {
                  code: res_one.code
                }).then(function (res_two) {

                })
              }
            })

          // }

        // })
      }, 1000);
    }

  },
  //页面统计
  pageStatistics(str){
    let parm = {
      type: str
    }
    fly.post('mall/v1/common/pageStatistics', parm)
      .then(function (res) {
      
      })   
  },
  //绑定spreadCode
  bindSpread(code,time){
    let that=this;
    let parm={
      spread_code:code,
      time:time
    }
    fly.post('v1/common/system/bindSpreadCode', parm)
        .then(function (res) {

    })   
  },
  //获取直播间分享者spread_code
  getSpreadCode(str) {
    let parm = {
      open_id: str
    }
    fly.post('mall/v1/common/miniLive/getSpreadCode', parm)
      .then(function (res) {
        if (res.code == "200") {
          wx.setStorageSync("spread_code", res.data.spread_code);
          var timestamp = Date.parse(new Date());
          timestamp = timestamp / 1000;
          wx.setStorageSync("time", timestamp)
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      })
  },
  //发送订阅消息
  requestMsg(e) {
    let that = this;
    wx.requestSubscribeMessage({
      tmplIds: [e],
      success(res) {
        console.log('成功')
      }, fail(res) {
        console.log('失败')
      },
      complete(res) {
        console.log(e)
        console.log('complete  调用完成')
      }
    })
  },
  //点击复制文本
  copyText: function (e) {
    wx.setClipboardData({
      data: e,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制成功',
              icon: 'none',
            })
          }
        })
      }
    })
  },
  globalData: {
    height: 0,//设备顶部窗口的高度
    titleBarHeight: 0,//标题栏高度
    share: 0,//判断是否是从分享页面进入
    windowHeight: 0,
    navHeight: 0,
    isGet: 0,
    cartNum: 0,
    isGo: true,
    closeIndex: '',
    redShow:false,
    store_id:0,
    windowWidth:0,
    is_live:0,//是否玩过游戏
    myRedNum:0,
    scene:0
  },
})